# encoding: utf-8
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
#   Mayor.create(name: 'Emanuel', city: cities.first)

def seed_enumerations(model, url)
  res = HTTParty.get(url)
  if (res.code == 200)
    h = Hash.from_xml(res.body)
    h['schema']['simpleType']['restriction']['enumeration'].each do |item|
      code = item['value']
      description_fin = item['annotation']['documentation'][0]
      description_swe = item['annotation']['documentation'][1]
      description_eng = item['annotation']['documentation'][2]
      entry = model.find_by_code(code)
      unless entry
        model.create({:code => code, :description_fin => description_fin, :description_swe => description_swe, :description_eng => description_eng})
      else
        entry.update_attributes({:code => code, :description_fin => description_fin, :description_swe => description_swe, :description_eng => description_eng})
      end
    end
  else
    puts "Failed to seed #{model.to_s} model. Maybe a networking issue?"
  end
end

# Seed counties
seed_enumerations(County, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/maakunta.xsd')
# Seed greater ares
seed_enumerations(GreaterArea, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/suuralue.xsd')
# Seed languages
seed_enumerations(Language, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/kieli.xsd')
# Seed language majorities
seed_enumerations(LanguageMajority, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/kieliEnemmisto.xsd')
# Seed language officialities
seed_enumerations(LanguageOfficiality, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/kieliVirallisuus.xsd')
# Seed location types
seed_enumerations(LocationType, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/paikkatyyppi.xsd')
# Seed location type groups
seed_enumerations(LocationTypeGroup, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/paikkatyyppiryhma.xsd')
# Seed location type subgroups
seed_enumerations(LocationTypeSubgroup, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/paikkatyyppialaryhma.xsd')
# Seed municipalities
seed_enumerations(Municipality, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/kunta.xsd')
# Seed provinces
seed_enumerations(Province, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/laani.xsd')
# Seed regions
seed_enumerations(Region, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/seutukunta.xsd')
# Seed scale relevancies
seed_enumerations(ScaleRelevancy, 'http://xml.nls.fi/Nimisto/Nimistorekisteri/mittakaavarelevanssi.xsd')

